package com.ruiysoft.controller.freight;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruiysoft.entity.feight.Freight;
import com.ruiysoft.entity.feight.FreightRegion;
import com.ruiysoft.entity.feight.FreightRegionEx;
import com.ruiysoft.entity.mdse.MerchandiseSku;
import com.ruiysoft.entity.mdse.MerchandiseSpu;
import com.ruiysoft.entity.sys.SysMicroShop;
import com.ruiysoft.entity.sys.SysRegion;
import com.ruiysoft.mapper.feight.FreightRegionMapper;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.service.feight.FreightRegionService;
import com.ruiysoft.service.feight.IFreightService;
import com.ruiysoft.service.mdse.IMerchandiseSkuService;
import com.ruiysoft.service.mdse.IMerchandiseSpuService;
import com.ruiysoft.service.sys.ISysRegionService;
import com.ruiysoft.service.sys.clent.LoginContextUtil;
import com.ruiysoft.service.sys.impl.SysRegionServiceImpl;
import com.ruiysoft.util.NumberUtils;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-11-10T22:47:21.301+08:00")

@RestController
public class FreightApiController implements FreightApi {

    private static final Logger log = LoggerFactory.getLogger(FreightApiController.class);

    @Autowired
    private IFreightService freightService;

    @Autowired
    IMerchandiseSpuService merchandiseSpuService;

    @Autowired
    IMerchandiseSkuService merchandiseSkuService;

    @Autowired
    FreightRegionService freightRegionService;

    @Autowired
    FreightRegionMapper freightRegionMapper;

    @Autowired
    private ISysRegionService sysRegionService;

    // postalCode 邮编； amount 支付金额； skuList skuid和数量
    @Override
    public Result<Map> freightGet(String postalCode, Long amount, String skuList) {
        if(postalCode == null || postalCode == "")
            return ResultGenerator.genFailResult("postalCode 不能为空！");
//        postalCode = sysRegionService.getOne(new QueryWrapper<SysRegion>().eq("zipcode",postalCode)).getAdcode();

        SysRegion sysRegion = sysRegionService.getOne(new QueryWrapper<SysRegion>().eq("zipcode",postalCode));
        if(sysRegion != null)
            postalCode = sysRegion.getAdcode();

        Map retMap = new HashMap();
        // 从spu列表中挑出运费最贵的返回，应为客户只承担一个订单的运费。一个订单店铺可能要给多家供应商付运费
        List<Map<String, Object>> list = JSON.parseObject(skuList, new TypeReference<List<Map<String, Object>>>() {});
        Long shopId = getShopId();
        try {
            for (Map<String, Object> map: list) {
                Integer skuId = (Integer) map.get("skuId");
                Integer quantity = (Integer) map.get("quantity");
                MerchandiseSku merchandiseSku = merchandiseSkuService.getById(skuId);

                Integer freightId = null;
                try {
                    freightId = Integer.parseInt(merchandiseSku.getFreightTemplateId());
                } catch (Exception error) {}

                if(freightId == null)
                    return ResultGenerator.genFailResult("运费模板未指定！");

                List<Freight> freightList = freightService.freightList(shopId, freightId.longValue(),null,null);
                if(null != freightList && !freightList.isEmpty()){
                    Freight freight = freightList.get(0);
                    List<FreightRegion> freightRegionList = freight.getFreightRegionList();
                    if(null != freightRegionList && !freightRegionList.isEmpty()){
                        Map<String,FreightRegion> adMap = new HashMap<>();
                        for(FreightRegion freightRegion:freightRegionList){
                            adMap.put(freightRegion.getAdcode(),freightRegion);
                        }
                        FreightRegion freightRegion = null;
                        freightRegion = adMap.get(postalCode);
                        if(null == freightRegion){
                            freightRegion = adMap.get(postalCode.substring(0,4)+"00");
                        }
                        if(null == freightRegion){
                            freightRegion = adMap.get(postalCode.substring(0,3)+"000");
                        }
                        if(null == freightRegion){
                            freightRegion = adMap.get(postalCode.substring(0,2)+"0000");
                        }
                        if(null == freightRegion){
                            freightRegion = adMap.get(postalCode.substring(0,1)+"00000");
                        }
                        if(null != freightRegion){
                            String info = freight.getInfo();
                            freight = new Freight();
                            BeanUtils.copyProperties(freightRegion,freight);
                            freight.setInfo(info);
                        }
                    }

                    Integer defaultCount = freight.getDefaultCount() != null ? freight.getDefaultCount() : 1;
                    Integer defaultFee = freight.getDefaultFee();
                    Integer increaseCount = freight.getIncreaseCount() != null ? freight.getIncreaseCount() : 1;
                    Integer increaseFee = freight.getIncreaseFee();

                    Long famount = 0l;
                    if(amount>=freight.getFullFee()){
                        famount = 0l;
                    }else{
                        if(quantity<=defaultCount){ //小于等于默认数量
                            famount = defaultFee.longValue();
                        }else{
                            Integer leftCount = quantity-defaultCount;
                            Integer leftAmount = (leftCount%increaseCount) == 0?leftCount/increaseCount*increaseFee:(leftCount/increaseCount +1)*increaseFee;
                            famount = new Long(defaultFee + leftAmount);
                        }
                    }
                    Long maxAmt = (Long)retMap.get("amount");
                    maxAmt = null == maxAmt?0l:maxAmt;
                    if(famount>=maxAmt) {
                        retMap.put("amount", famount);
                        retMap.put("freight", freight);
                    }
                }
            }

            return ResultGenerator.genSuccessResult(retMap);

        } catch (Exception e) {
            log.error("商铺查询运费--{}",shopId, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    private Long getShopId() {
        SysMicroShop shop = LoginContextUtil.instance().getEntryMicroShop();
        return shop.getId();
    }

    @Override
    public Result<Void> freightSavePost(@ApiParam(value = ""  )  @Valid @RequestBody Freight freight) {
        Long shopId = getShopId();
        try{
            freight.setShopId(shopId);
            freightService.saveFreight(freight);
            return ResultGenerator.genSuccessResult();
        }catch (Exception e){
            log.error("商铺设置运费--{}--{}",shopId,JSONObject.toJSONString(freight), e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<Void> freightUpdatePost(@ApiParam(value = ""  )  @Valid @RequestBody Freight freight) {
        Long shopId = getShopId();
        try{
            freight.setShopId(shopId);
            freightService.updateFreight(freight);
            return ResultGenerator.genSuccessResult();
        }catch (Exception e){
            log.error("商铺修改运费模版--{}--{}",shopId,JSONObject.toJSONString(freight), e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<Object> getFreightList(String freightName, String adcode) {
        Long shopId = getShopId();
        List list = freightService.freightList(shopId,null,freightName,adcode);

        return ResultGenerator.genSuccessResult(list);
    }

    @Override
    public Result<Object> createOrEdit(Freight body) {
        Long shopId = getShopId();
        Freight freight = JSON.parseObject(JSON.toJSONString(body), new TypeReference<Freight>() {});
        if(freight != null)
            freight.setShopId(shopId);

        if(freightService.saveOrUpdate(freight))
            return ResultGenerator.genSuccessResult();
        return ResultGenerator.genFailResult("操作失败");
    }

    @Override
    public Result<Object> deleteById(String id) {
        if(freightService.removeById(id))
            return ResultGenerator.genSuccessResult();
        return ResultGenerator.genFailResult("操作失败");
    }

    @Override
    public Result<Object> createOrEdit4FreightRegion(List<FreightRegion> list) {
        for (FreightRegion freightRegion : list
             ) {
            if(!freightRegionService.saveOrUpdate(freightRegion))
                return ResultGenerator.genFailResult("操作失败");
        }

        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result<Object> getFreighRegiontList(Integer freighId) {
//        List list = freightRegionService.list(new QueryWrapper<FreightRegion>().eq("freight_id", freighId));
        List<FreightRegionEx> list = freightRegionMapper.leftjoinSysRegion(freighId);
        return ResultGenerator.genSuccessResult(list);
    }

    @Override
    public Result<Object> deleteById4FreighRegiont(Integer id) {
        int rtn = freightRegionMapper.deleteById(id);
        if(rtn > 0)
            return ResultGenerator.genSuccessResult(rtn);
        return ResultGenerator.genFailResult("操作失败");
    }

}
